package main

import (
	"context"
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"imooc-product/backend/web/controllers"
	mymongo "imooc-product/mongo"
	"imooc-product/repositories"
	"imooc-product/services"
)

func main()  {
	//1.创建Iris实例
	app := iris.New()
	//2.设置错误模式，在mvc模式下提示错误
	app.Logger().SetLevel("debug")
	//3.注册模板
	tmplate := iris.HTML("./web/views",".html").Layout("shared/layout.html").Reload(true)
	app.RegisterView(tmplate)
	//4.设置模板目录
	//app.HandleDir("/assets","./backend/web/assets")
	app.StaticWeb("/assets","./backend/web/assets")
	//5.出现异常跳转到指定页面
	app.OnAnyErrorCode(func(context iris.Context) {
		context.ViewData("message",context.Values().GetStringDefault("message","访问的页面出错"))
		context.ViewLayout("")
		context.View("shared/error.html")
	})
	//连接数据库
	db,err := mymongo.Get()
	if err != nil{
		fmt.Println(err)
		return
	}
	ctx,cancel := context.WithCancel(context.Background())
	defer cancel()
	//6.注册控制器
	productRepository := repositories.NewProductManager("product",&db)
	productService := services.NewProductService(productRepository)
	productParty := app.Party("/product")
	product := mvc.New(productParty)
	product.Register(ctx,productService)
	product.Handle(new(controllers.ProductController))


	//7.启动服务
	app.Run(
		iris.Addr("localhost:8080"),
		iris.WithoutServerError(iris.ErrServerClosed),
		iris.WithOptimizations,
		)
}
